package com.freejava.myblog.controller;

import com.alibaba.fastjson.JSONObject;
import com.freejava.myblog.annotation.PassToken;
import com.freejava.myblog.pojo.MyUser;
import com.freejava.myblog.services.TokenService;
import com.freejava.myblog.services.UserService;
import com.freejava.myblog.tools.JsonResultObject;
import com.freejava.myblog.tools.LoginUser;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/v1")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;

    /**
     * 注册接口
     * 注册、登录接口，一定是游客可以操作的
     * @param user 包含了用户名和密码信息
     * @RequestBody 数据需要放在请求body中，并且以json的形式传递，还要添加一个请求头，表示说请求内容是json格式
     * @return
     */
    @PassToken
    @PostMapping("/register")
    public JsonResultObject register(@RequestBody MyUser user) {
        return userService.register(user);
    }

    @PassToken
    @PostMapping("/login")
    public JsonResultObject login(@RequestBody LoginUser loginUser) {

        JsonResultObject result = userService.login(loginUser);

        if (result.getErrorMessage() != "") {
            return result;
        } else {
            String token = tokenService.getToken((MyUser) result.getData());
            JSONObject returnOject = new JSONObject();

            returnOject.put("token", token); // {token: "sdfdsfewaefraera2332343dc"}
            result.setData(returnOject); // 把token放入返回的json对象中的data部分
            return result;
        }
    }
}
